package com.qianfeng.zhangwei.fruitday.utils;

import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.zhangwei.fruitday.config.AppConfig;
import com.qianfeng.zhangwei.fruitday.widget.EmptyLayout;

/**
 * @说 明： 联网请求封装工具类
 * @项目名称：Sz1504Adv
 * @包 名： com.qianfeng.zhangwei.fruitday.utils
 * @类 名： HttpHelper
 * @创 建人： zhangwei
 * @创建时间：2015-08-08 15:14
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class HttpHelper<T> {
    private HttpUtils httpUtils;
    public OnSuccessCallBack callBack;


    public HttpHelper() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }

    }


    public HttpHandler<String> sendPost(RequestParams params, final Class<T> cls) {
        HttpHandler<String> handler = httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.REQUEST_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                T t = JSONObject.parseObject(responseInfo.result, cls);
                if (t != null && callBack != null) {
                    callBack.onSuccessCallBack(t);
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }

        });

        return handler;
    }

    public HttpHandler<String> sendPost(final EmptyLayout emptyLayout, RequestParams params) {
        HttpHandler<String> handler = httpUtils.send(HttpRequest.HttpMethod.POST, AppConfig.REQUEST_URL, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                emptyLayout.dismiss();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                emptyLayout.setErrorType(EmptyLayout.NODATA_ENABLE_CLICK);
            }

            @Override
            public void onCancelled() {
                super.onCancelled();
                emptyLayout.dismiss();
            }
        });
        return handler;
    }


    public interface OnSuccessCallBack {
        public <T> void onSuccessCallBack(T t);
    }

    public OnSuccessCallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(OnSuccessCallBack callBack) {
        this.callBack = callBack;
    }
}
